import React, { useState, useEffect, ReactNode } from 'react';
import './index.scss';
import { PopupType } from './type';

// 弹出框
function Popup(props: PopupType) {
  const [visible, setVisible] = useState<Boolean | undefined>(false);
  const [title] = useState(props.title || '提示');
  const [children, setChildren] = useState<ReactNode>(props.children || <></>);
  /**
   * 操作
   * @param {boolean} visible 监听父组件传递的 visible 状态
   */
  useEffect(() => {
    let _visible = props.visible;
    let _children = props.children;
    setVisible(_visible);
    if (_visible) {
      setChildren(_children);
    } else {
      setChildren(<></>)
    }
  }, [props]);
  // 切换弹出框是否显示
  const popupChange = (e: any) => {
    setVisible(!visible);
    props.onChange();
  }
  // 返回
  return (
    <div className={`popup ${visible ? 'show' : 'hide'}`}>
      <div className="maskLyer" onClick={popupChange}></div>
      <div className="popupBox">
        <div className="titleBox">
          <div className="message">{title}</div>
          <div className="btn icon-error" onClick={popupChange} />
        </div>
        <div className="contentBox">
          {children}
        </div>
      </div>
    </div>
  );
}

export default Popup;